package com.treasure.mall.biz.base;


import com.treasure.mall.biz.dto.BaseSearchDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.io.Serializable;
import java.util.List;

/**
 * @author allan
 * @date 09/11/2017
 */
public abstract class AbstractSearchableCrudService<T, ID extends Serializable> extends AbstractCrudService<T, ID> implements SearchableCrudService<T, ID> {
    protected final JpaSearchableRepository<T, ID> repository;

    protected AbstractSearchableCrudService(JpaSearchableRepository<T, ID> repository) {
        super(repository);
        this.repository = repository;
    }

    @Override
    public Page<T> findAll(int pageIndex, int pageSize, BaseSearchDTO searchDTO) {
        SpecificationAndSort<T> specificationAndSort = specificationAndSort(searchDTO);
        PageRequest pageRequest;
        if (specificationAndSort.getSort() == null) {
            pageRequest = PageRequest.of(pageIndex - 1, pageSize);
        } else {
            pageRequest = PageRequest.of(pageIndex - 1, pageSize, specificationAndSort.getSort());
        }

        return repository.findAll(specificationAndSort.getSpecification(), pageRequest);
    }

    @Override
    public Page<T> findAll(int pageIndex, int pageSize) {
        return repository.findAll(PageRequest.of(pageIndex - 1, pageSize));
    }

    /**
     * 得到所有记录
     *
     * @return
     */
    @Override
    public List<T> findAll() {
        return repository.findAll();
    }

    /**
     * 创建一个Specification
     *
     * @param searchDTO 查询条件
     * @return {@link SpecificationAndSort<T>}
     */
    protected abstract SpecificationAndSort<T> specificationAndSort(BaseSearchDTO searchDTO);

    protected String likeFormat(String field) {
        return "%" + field + "%";
    }
}
